<?php

namespace App\Http\Controllers\Api;

use App\Http\Services\AliCloudService;
use App\Http\Services\FaceService;
use App\Models\AccountRecord;
use App\Models\Allblacklist;
use App\Models\Autoreply;
use App\Models\AutoreplyGroup;
use App\Models\Config;
use App\Models\Enlist;
use App\Models\EnlistWeixin;
use App\Models\Fraud;
use App\Models\Income;
use App\Models\Jump;
use App\Models\Kefu;
use App\Models\Lastvisit;
use App\Models\Matchpool;
use App\Models\Member;
use App\Models\MemberBan;
use App\Models\MemberCheck;
use App\Models\Msg;
use App\Models\OfficialAccountSubscribe;
use App\Models\PublicAccountPush;
use App\Models\ShortLink;
use App\Models\Sign;
use App\Models\UpdateAvatarLog;
use App\Models\Withdraw;
use App\Repositories\AccountRecordRepository;
use App\Repositories\Api\ChatRepository;
use App\Repositories\Api\ElectPoolRepository;
use App\Repositories\Api\EnlistRepository;
use App\Repositories\Api\JumpRepository;
use App\Repositories\Api\MemberMatchRepository;
use App\Repositories\Api\MemberMiniRecommendRepository;
use App\Repositories\Api\MemberRepository;
use App\Repositories\Api\MemberVisitOrderRepository;
use App\Repositories\Api\WechatMenusRepository;
use App\Repositories\AreaRepository;
use App\Repositories\BlacklistRepository;
use App\Repositories\CreditRepository;
use App\Repositories\FileRepository;
use App\Repositories\MemberQrcodeRepository;
use App\Repositories\MemberVisitRepository;
use App\Repositories\PictureMappingRepository;
use App\Repositories\RechargeComboRepository;
use App\Repositories\WechatRepository;
use Exception;

class MemberController extends MiniAppController
{
    /**
     * @var
     */
    private $memberRep,
        $wechatRep,
        $wechatMenusRep;

    const CHECK_SIMILAR_FIELDS = [
        'residence',
        'username',
        'work_or_study_place',
        'famliy_condition',
        'about_you',
        'about_me',
        'undergraduate',
        'master_college',
        'doctor_college',
        'profession',
        'work_org',
    ];//检查相似度

    const  MINI_WIDTH = 120;
    const  OPEN_LOCK_VISIT = 6;

    public function __construct(
        MemberRepository      $memberRep,
        WechatMenusRepository $wechatMenusRep,
        WechatRepository      $wechatRep
    )
    {
        parent::__construct();
        $this->memberRep = $memberRep;
        $this->wechatRep = $wechatRep;
        $this->wechatMenusRep = $wechatMenusRep;
    }

    public function update()
    {
        $params = request()->all();
        $code = 1;
        $return = [];

        $categories = $this->memberRep->getMemberCategoryForMember();

        $category_ids = get_column($categories, 'id');
        $current_index = array_search($params['type'], $category_ids);
        $categories = ass_column($categories, "id");

        $category = $categories[$params['type']];

        if (!$category)
            return $this->apiResponse->error("类型不存在", 400);

        $member = $this->memberRep->getOne($params['wechat_admin_id']);

        if ($category['id'] == 6) {
            $data['picture_ids'] = $params['picture_ids'];

            if (count($data['picture_ids']) == 0)
                return $this->apiResponse->error("图片必填", 400);

            $res = (new PictureMappingRepository())->updateMapping($params['wechat_admin_id'], "member", $params['picture_ids']);
        } else {

            $data = [];
            foreach ($category['fields'] as $k => $v) {
                if (in_array($v, ['id', 'mobile', 'status', 'credit'])) continue; //不许更新

                if (in_array($v, ['username', 'avatar', 'hometown', 'location', 'work_or_study_place', 'residence', 'weixin', 'qq', 'master_college', 'doctor_college', 'profession', 'work_org', 'occupation', 'family_condition', 'about_me', 'about_you'])) {
                    $data[$v] = !empty($params[$v]) ? $this->pre_attack($params[$v]) : '';
                    continue;
                } else {
                    $data[$v] = isset($params[$v]) ? $params[$v] : '';
                }
            }

            //检测微信二维码 是否有效 ToDo
            if ($params['type'] == 3 && $params['weixin_qrcode_pic']) {
                $result = cos_check_qrcode($params['weixin_qrcode_pic']);
                if (!$result) {
                    return $this->apiResponse->error("检测到你上传的图片不是微信二维码，或是微信二维码但背景色非白色。系统暂只支持识别白色背景的微信二维码，请重新上传！");
                } else {
                    $data['enable_wx_qrcode'] = 1;
                }
            }

            if (count($data) == 0)
                return $this->apiResponse->error("更新信息不能为空");

            //年龄不许改小
            if ($member['birthday']) {
                if (!is_str_has($member['birthday'], '0000')) {
                    $old_birthday = substr($member['birthday'], 0, 4);

                    if (intval($data['birthday'][0]) > intval($old_birthday)) {
                        return $this->apiResponse->error("年龄不许改小，如需修改加请管理员微信bsbly88提供身份证修改！", 400);
                    }
                }
            }

            if (!empty($data["gender"]) && $data["gender"] != $member['gender']) {
                $data["is_update_gender"] = 1;
                (new ElectPoolRepository())->update_electpool_num_by_gender($params['wechat_admin_id'], $data["gender"]);
            }

            if (strpos($data["current_status"], '在读') !== false && strpos($member["current_status"], '工作') !== false) {
                return $this->apiResponse->error("目前状态不允许由工作自行改为在读，如需修改请点红字链接修改！", 400);
            }

            if (strpos($data["current_status"], '大') !== false && strpos($member["current_status"], '研') !== false) {
                return $this->apiResponse->error("目前状态不允许由研究生在读改为本科在读，如需修改请点红字链接修改！", 400);
            }

            if ((strpos($data["current_status"], '大') !== false || strpos($data["current_status"], '研') !== false) && strpos($member["current_status"], '博') !== false) {
                return $this->apiResponse->error("目前状态不允许由博士在读改为本硕在读，如需修改请点红字链接修改！", 400);
            }

            $data['is_update_profile'] = 1;
            if ($category['id'] && $member['idcard_status'] == 1) {
                unset($data['gender']);
                unset($data['birthday']);
            }

            //状态0和1可以修改
            if (!in_array($member['status'], [0, 2]) && $category['id'] == 4) {
                unset($data['undergraduate']);
            }

            if (empty($data['gender'])) {
                unset($data['gender']);
            }

            $res = $this->memberRep->saveOrUpdate($data, $params['wechat_admin_id']);
        }


        if ($params['type'] == 6) {
            if ($member['pictures'] && count($data['picture_ids']) >= 2) {
                //完善资料奖励
                $reward = $this->memberRep->profile_reward($params['type'], $member);
            }
        }

        $msg = '更新成功';
        if ($params['type'] == 12) {
            $result = $this->_check_avatar_face($data['avatar']);
            $add['uid'] = UID;
            $add['text'] = var_export($result, true);
            $add['path'] = $data['avatar'];
            $add['create_time'] = date('Y-m-d H:i:s');
            UpdateAvatarLog::insert($add);

            $avatar_width = $result['data']['FaceDetailInfos'][0]['FaceRect']['Width'];
            if ($result['code'] == 0 && $result['codeError'] != 'FailedOperation.ImageDownloadError') {
                $avatar_check = 0;
                $in['avatar_status'] = 2;//非图片下载失败并且机器审核返回0则判定为无效头像
                $msg = "未检测到图片有人脸或人脸过小系统无法识别，头像不合格，请重新上传，否则将无法选择头像合格的嘉宾！";
                $code = 0;
            }
            if ($result['codeError'] == 'FailedOperation.ImageDownloadError') {
                $in['avatar_status'] = 1;
            }
            if ($result['code'] == 1 && $avatar_width < self::MINI_WIDTH) {
                $in['avatar_status'] = 2;
                $msg = "本次上传的头像中人脸宽度为" . $avatar_width . "像素，低于系统合格要求" . self::MINI_WIDTH . "像素，请重新上传（可以适当拉伸放大头像），否则将无法选择头像合格的嘉宾！";
                $code = 0;
            }
            if ($avatar_width >= self::MINI_WIDTH) {
                $in['avatar_status'] = 1;
                $in['avatar_check'] = 1;
            }
            if ($result['code'] == 0) {
                $avatar_width = 0;
            }
            $in['avatar_check'] = 1; //新数据
            $in['avatar'] = $data['avatar'];
            $in['avatar_qrcode_state'] = 1;
            $in['avatar_qrcode_url'] = '';
            $in['avatar_width'] = $avatar_width;

            //添加到审核表
            MemberCheck::where([
                'uid' => UID,
                'object_type' => "avatar",
                'check_status' => 2
            ])->update([
                'check_status' => 1,
                'check_time' => date("Y-m-d H:i:s"),
            ]);
            $mc_data['data'] = json_encode([
                'avatar_qrcode_state' => 1,
                'avatar_qrcode_url' => "",
                'avatar_width' => $avatar_width,
                'avatar_status' => $in['avatar_status'],
                'avatar_check' => $avatar_check,
                'avatar' => $in['avatar'],
            ]);
            $mc_data['status'] = $in['avatar_status'];
            $mc_data['uid'] = UID;
            $mc_data['object_type'] = "avatar";
            MemberCheck::create($mc_data);

            //头像检测不合格通知
            if (!empty($member['openid']) && $in['avatar_status'] == 2) {
                sendTemplateMsg($member['openid'], 1, [
                    'wo_uid' => $member['id'],
                    'content' => '你上传的头像中的人脸宽度为' . $avatar_width . '像素，低于合格要求' . self::MINI_WIDTH . '像素，被系统判定为无效头像，请点击重新上传，保证头像中的人脸宽度不小于90像素。',
                    'page' => "member/info/edit_avatar"
                ], 18);
            }

            $this->memberRep->updateFields($params['wechat_admin_id'], $in);
            $return['avatar_width'] = $avatar_width;
        }

        // 关于我 关于你 大于50字奖励
        if ($params['type'] == 9 && mb_strlen($data['about_you']) >= 20 && mb_strlen($data['about_me']) >= 20) {
            $reward = $this->memberRep->profile_reward($params['type'], $member);
        }

        //完善资料奖励
        if (in_array($params['type'], [1, 2, 4, 5, 8])) {
            $reward = $this->memberRep->profile_reward($params['type'], $member);
        }

        $perfect = $this->memberRep->check_member_profile();
        if (!empty($perfect['type'])) {
            $next_type = $params['type'] != $perfect['type'][0] ? $perfect['type'][0] : (isset($perfect['type'][1]) ? $perfect['type'][1] : 0);
        } else {
            $next_type = 0;
        }
        $return['next_type'] = $next_type;
        $return['code'] = $code ?? 1;

        return $this->apiResponse->success($return, $msg);
    }

    private function _check_avatar_face($img_path)
    {
        $data = (new FaceService())->update_member_avatar_width('https://bsbly-1253457105.cos.ap-shanghai.myqcloud.com' . $img_path);
        return $data;
    }

    public function detail()
    {
        $admin = $this->memberRep->getOne(UID);
        $admin['stepby'] = $this->memberRep->check_member_profile();

        return $this->apiResponse->success($admin ?? []);
    }

    /**
     * 账户明细
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-10T19:21:47+0800
     * @param string $value [description]
     * @return   [type]                           [description]
     */
    public function account_record()
    {
        $params = request()->only("type", "wechat_admin_id");
        $res = (new AccountRecordRepository())->getPages($params, $this->pageSize, $this->pageNum);
        return $this->apiResponse->success($res);
    }

    public function account_record_detail()
    {
        $id = request()->get("id");
        $res = (new AccountRecordRepository())->getOne($id);
        return $this->apiResponse->success(['record' => $res]);
    }

    /**
     * 获取快速编辑自己了方式
     * @return array|mixed|string
     */
    public function quick_profile()
    {
        $fields = $this->memberRep->getMemberQuickFields();
        $member = $this->memberRep->getOne(UID);

        return $this->apiResponse->success([
            'fields' => $fields,
            'member' => $member
        ]);
    }

    /**
     * 快速完善保存
     * @return
     */
    public function update_quick()
    {
        $params = request()->all();
        $member = $this->memberRep->getOne(UID);
        $fields = $this->memberRep->getMemberQuickFields();

        $fieldKeys = array_keys($fields);

        $data = [];
        foreach ($fieldKeys as $k => $v) {
            if (in_array($v, ['id', 'mobile', 'status', 'credit'])) continue; //不许更新

            if (in_array($v, ['username', 'hometown', 'location', 'work_or_study_place', 'residence', 'weixin', 'qq', 'master_college', 'doctor_college', 'profession', 'work_org', 'occupation', 'family_condition', 'about_me', 'about_you'])) {
                $data[$v] = !empty($params[$v]) ? $this->pre_attack($params[$v]) : '';
                continue;
            } else {
                $data[$v] = isset($params[$v]) ? $params[$v] : '';
            }
        }

        if (count($data) == 0)
            return $this->apiResponse->error("更新信息不能为空");

        //年龄不许改小
        if ($member['birthday']) {
            if (!is_str_has($member['birthday'], '0000')) {
                $old_birthday = substr($member['birthday'], 0, 4);

                if (intval($data['birthday'][0]) > intval($old_birthday)) {
                    return $this->apiResponse->error("年龄不许改小，如需修改加请管理员微信bsbly88提供身份证修改！", 400);
                }
            }
        }

        if (!empty($data["gender"]) && $data["gender"] != $member['gender']) {
            $data["is_update_gender"] = 1;
            (new ElectPoolRepository())->update_electpool_num_by_gender($params['wechat_admin_id'], $data["gender"]);
        }

        if (strpos($data["current_status"], '在读') !== false && strpos($member["current_status"], '工作') !== false) {
            return $this->apiResponse->error("目前状态不允许由工作自行改为在读，如需修改请点红字链接修改！", 400);
        }

        if (strpos($data["current_status"], '大') !== false && strpos($member["current_status"], '研') !== false) {
            return $this->apiResponse->error("目前状态不允许由研究生在读改为本科在读，如需修改请点红字链接修改！", 400);
        }

        if ((strpos($data["current_status"], '大') !== false || strpos($data["current_status"], '研') !== false) && strpos($member["current_status"], '博') !== false) {
            return $this->apiResponse->error("目前状态不允许由博士在读改为本硕在读，如需修改请点红字链接修改！", 400);
        }

        $data['is_update_profile'] = 1;
        if (empty($data['gender'])) {
            unset($data['gender']);
        }

//        $res = $this->memberRep->saveOrUpdate($data, $params['wechat_admin_id']);
        // 关于我 关于你 大于50字奖励

        if (mb_strlen($data['about_you']) >= 20 && mb_strlen($data['about_me']) >= 20) {
            $reward = $this->memberRep->profile_reward($params['type'], $member);
        }

        // ToDo  完善资料奖励
        if (in_array($params['type'], [1, 2, 4, 5, 8])) {
            $reward = $this->memberRep->profile_reward($params['type'], $member);
        }

        $perfect = $this->memberRep->check_member_profile();
        if (!empty($perfect['type'])) {
            $next_type = $params['type'] != $perfect['type'][0] ? $perfect['type'][0] : (isset($perfect['type'][1]) ? $perfect['type'][1] : 0);
        } else {
            $next_type = 0;
        }
        return $this->apiResponse->success(['next_type' => $next_type], "更新成功");
    }

    public function profile()
    {
        $isEdit = request()->get("isEdit", 0);
        $fields = $this->memberRep->getMemberFields();
        $member = $this->memberRep->getOne(UID);

        if ($isEdit) {
            $categories = $this->memberRep->getMemberCategoryForMember();
        } else {
            $categories = (new WechatMenusRepository())->getMemberCategoryForProfile();
        }

        if (intval($member['idcard_status']) == 1) {
            unset($categories[10]);
        }

        if (in_array($member['status'], [1, 3])) {
            unset($categories[11]);
        }

        if ($isEdit) {
            $unset_fields = ['mobile', 'status', 'credit', 'jw_location'];
            foreach ($categories as $k => $v) {
                if ($member['idcard_status'] == 1) {
                    $unset_fields[] = 'gender';
                    $unset_fields[] = 'birthday';

                    if (empty(!$member['ismyself'])) {
                        $unset_fields[] = 'ismyself';
                    }
                }

                in_array($member['status'], [1, 3, 4]) && $unset_fields[] = 'undergraduate';
                $member["is_update_gender"] == 1 && $unset_fields[] = 'gender';

                foreach ($v['fields'] as $sk => $sv) {
                    if (in_array($sv, $unset_fields)) {
                        unset($categories[$k]['fields'][$sk]);
                    }
                }
            }

            $categories = ass_column($categories, "id");
        }

        return $this->apiResponse->success([
            'fields' => $fields,
            'member' => $member,
            'categories' => $categories,
        ]);
    }

    /**
     * 上传文件
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-17T18:05:32+0800
     * @return   [type]                   [description]
     */
    public function upload()
    {
        $field_key = request()->get("field_key");
        $pic_mid = request()->get("id");
        $fileData = request()->file('fileData');

        $file_type = ""; //默认文件夹
        if ($field_key == 'avatar') {
            $file_type = "avatar";
        } elseif ($field_key == 'weixin_qrcode_pic') {
            $file_type = "wxqrcode";
        } elseif ($field_key == 'education_pic') {
            $file_type = "education";
        } elseif ($field_key == 'id_front_pic') {
            $file_type = "idcard";
        } else {
            $file_type = "member";
        }

        if ($field_key == 'picture') {
            $file_type = 'member_picture';
        }

        $res = app(FileRepository::class)->upload($fileData, $file_type, null, $file_type . '_' . md5(UID));
        if ($field_key == 'picture' && !empty($res)) {

            $pic_id = (new PictureMappingRepository())->updateSimpleMapping($pic_mid ?? "", UID, 'member', $res['id']);
            if ($pic_id) {
                $res['picture_id'] = $res['id'];
                $res['id'] = $pic_id;
            }
        }

        $res['size'] = formatBytes($res['size']);
        $res['full_path'] = getPreviewImage($res['full_path']);

        return $this->apiResponse->success($res, "ok");
    }

    /**
     * 获取套餐
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-28T14:17:29+0800
     * @return   [type]                   [description]
     */
    public function get_combo()
    {
        $wechat_admin_id = request()->get("wechat_admin_id");
        $rechare_combos = (new RechargeComboRepository())->get_recharge_prices($wechat_admin_id, 1);
        $return['combos'] = $rechare_combos;

        $profile_check = $this->memberRep->check_member_profile();
        $member = $this->memberRep->getOne(UID);
        if (!$profile_check['is_all'] || in_array($member['idcard_status'], [0, 2]) || in_array($member['status'], [0, 2])) {
            if ($member['idcard_status'] == 0 || $member['idcard_status'] == 2) {
                $profile_check['type'][] = 7;
            }

            if ($member['status'] == 0 || $member['status'] == 2) {
                $profile_check['type'][] = 10;
            }

            //获取新手任务
            $tasks = new_task_list();
            // $taskArr = new_task_list();

            // //奖励栏目
            // $tasks = [
            //   10 => $taskArr[10],
            //   7 => $taskArr[7],
            //   99 => $taskArr[99],
            // ];
            foreach ($tasks as $k => $v) {
                if (!in_array($k, $profile_check['type'])) {
                    unset($tasks[$k]);
                }
            }
            $return['tasks'] = $tasks;
        }

        // 签到信息
        $return['is_sign'] = Sign::where(["uid" => UID])->where("create_time", ">=", strtotime(date('Y-m-d')))->count("id");
        if ($member['current_status'] && is_str_has($member['current_status'], '在读')) {
            //高校脱单
            $return['sign_link'] = C('sign_link');
        } else {
            //高知脱单
            $return['sign_link'] = C('sign_link');
        }

        // if($member['birthday'] && $member['height']){
        //     $res['is_all'] = 1;
        //     $return['check_profile'] = $res;
        // }else if(empty($member['birthday']) && empty( $member['height'])){
        //     $res['is_all'] = 0;
        //     $return['check_profile'] = $res;
        // }
        $return['check_profile'] = $profile_check;
        $return['sign_price'] = '2.5';
        $return['is_ios_recharge'] = C('is_ios_recharge');//ios能否直接充值,1-不能充值 0-可以充值
        return $this->apiResponse->success($return);
    }

    /**
     * 加入黑名单
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-25T10:35:13+0800
     */
    public function add_black()
    {
        $wechat_admin_id = request()->get("wechat_admin_id");
        $amount = Allblacklist::where("uid", "=", $wechat_admin_id)->count("id");

        if ($amount > 14) {
            return $this->apiResponse->error("超出15个限制，请先删除部分被屏蔽嘉宾！", 400);
        }
        $params = request()->only("query", "id");

        if (UID == $params['id']) {
            return $this->apiResponse->error("不能屏蔽本人！");
        }

        if ($params['id']) {
            $ids = Member::where("id", "=", $params['id'])->pluck("id")->toArray();
        } else if ($params['query']) {
            $ids = Member::where(function ($q) use ($params) {
                $q->where('weixin', "=", $params['query'])
                    ->orWhere("mobile", "=", $params['query']);
            })
                ->pluck("id")
                ->toArray();
        }

        if ($ids) {
            foreach ($ids as $k => $v) {
                $data['uid'] = $wechat_admin_id;
                $data['black_uid'] = $v;
                $data['input'] = $params['query'] == "" ? $params['id'] : $params['query'];
                $data['create_time'] = date("Y-m-d H:i:s");
                Allblacklist::insert($data);
            }
        } else {
            $data['uid'] = $wechat_admin_id;
            $data['status'] = 0;
            $data['input'] = $params['query'] == "" ? $params['id'] : $params['query'];
            $data['create_time'] = date("Y-m-d H:i:s");
            Allblacklist::insert($data);
        }

        return $this->apiResponse->success([], "ok");
    }

    /**
     * 屏蔽列表
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-30T22:57:28+0800
     * @return   [type]                   [description]
     */
    public function blacklist()
    {
        $filter = request()->only("wechat_admin_id");

        $res = (new BlacklistRepository())->getPages($filter, $this->pageSize, $this->pageNum);

        return $this->apiResponse->success($res);
    }

    /**
     * 删除屏蔽
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-30T23:26:48+0800
     * @return   [type]                   [description]
     */
    public function delete_black()
    {

        $id = intval(request()->post("id"));
        //$wechat_admin_id = request()->get("wechat_admin_id");

        if (!$id)
            return $this->apiResponse->error("参数错误");

        $list = Allblacklist::where(['id' => $id])->first();

        if ($list['uid'] != UID)
            return $this->apiResponse->error("无权限删除");

        Allblacklist::where(['id' => $id])->delete();

        return $this->apiResponse->success([], "ok");
    }

    public function update_field()
    {
        $field_key = request()->post("field_key");
        $wechat_admin_id = request()->get("wechat_admin_id");

        $params = request()->all();
        $member = $this->memberRep->getOne(UID);

        foreach (self::CHECK_SIMILAR_FIELDS as $k => $v) {
            if (empty($params[$v])) continue;
            //检查是否包含微信
            if (check_strs_similar($member["weixin"], $params[$v]) >= 0.2 && $field = $this->memberRep->getMemberQuickFields($v)) {
                return retFail($field['title'] . '可能包含微信号，修改后再保存哦!');
            }

            //检查是否包含手机号码
            if (check_strs_similar($member["mobile"], $params[$v]) >= 0.2 && $field = $this->memberRep->getMemberQuickFields($v)) {
                return retFail($field['title'] . '可能包含手机号，修改后再保存哦!');
            }

            if (in_array($v, ['about_me', 'about_you']) && mb_strlen($params[$v]) < 20) {
                return retFail(($field['title'] ?? "") . '不能少于20字');
            }
        }

        if ($field_key == 'weixin_qrcode_pic') { // 检测微信二维码
            $weixin_qrcode_pic = request()->post("weixin_qrcode_pic", "");

            $result = check_img_qr_code($weixin_qrcode_pic);
            if (!$result) {
                return retFail("检测到你上传的图片不是微信二维码，或是微信二维码但背景色非白色。系统暂只支持识别白色背景的微信二维码，请重新上传！");
            }
        }

        if ($field_key && in_array($field_key, ['avatar', 'username', 'gender', 'homosex_visibility', 'enlist_need_verify_profile', 'accept_enlist_message', 'is_allow_fatie_push', 'is_nearby', 'award_type'])) {
            $data[$field_key] = request()->post($field_key);

            if (strlen($data['birthday']) == 7) {
                // 解决提交的生日数据为 1996-00 ，保存报错的情况
                $data['birthday'] = str_replace('00', '06', $data['birthday']) . '-01';
            }

            $this->memberRep->saveOrUpdate($data, $wechat_admin_id);
        } else {
            $data = request()->all();
            unset($data['wechat_admin_id']);
            unset($data['s']);
            if (!empty($data['field_key'])) {
                unset($data['field_key']);
            }

            foreach (['height_from', 'height_to', 'birth_to', 'birth_from', 'current_status', 'education'] as $k => $v) {
                if (!isset($data[$v])) continue;
                if ($data[$v] == '不限') {
                    $data[$v] = 0;
                }
            }

            if (!empty($data['pictures']) && count($data['pictures']) >= 2) {
                $res = (new PictureMappingRepository())->updateMapping(UID, "member", $data['pictures']);
                if ($res) {
                    //完善资料奖励
                    $member = $this->memberRep->getOne(UID);
//                    $reward = $this->memberRep->profile_reward(6, $member);
                }
            } else {
                $this->memberRep->saveOrUpdate($data, $wechat_admin_id);
            }

        }
        if (!empty($data['gender'])) {
            //并且删除今天的推荐
            (new MemberMatchRepository())->deleteUids(UID);
        }


        return $this->apiResponse->success([], 'ok');
    }

    /**
     * 设置中字段
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-30T14:06:54+0800
     */
    public function set_field()
    {
        $member = $this->memberRep->getOne(UID);
        $pre_fix = $member['gender'] == "F" ? '他' : '她';

        $member_height = member_height();
        $member_make_birth = member_make_birth();
        $fields = [
            'blacklist' => [
                'icon' => "set_user",
                'title' => "屏蔽",
                'type' => "link",
                'url' => "blacklist/index"
            ],

            'cancel' => [
                'icon' => "set_logout",
                'title' => "注销",
                'type' => "link",
                'url' => "member/cancel"
            ],
        ];

        return retSuc(compact("member", "fields"));
    }

    /**
     * 注销账户
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-30T10:16:04+0800
     * @return   [type]                   [description]
     */
    public function cancel()
    {
        $this->memberRep->updateFields(request()->get("wechat_admin_id"), ['cancel' => 0]);
        return $this->apiResponse->success([], '注销成功');
    }

    /**
     * 恢复账户
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-30T10:16:04+0800
     * @return   [type]                   [description]
     */
    public function recover()
    {
        $this->memberRep->updateFields(request()->get("wechat_admin_id"), ['cancel' => 1]);
        return $this->apiResponse->success([], '恢复成功');
    }


    public function get_areas()
    {
        $type = request()->get("type");
        if ($type == 1) {
            $areas = (new AreaRepository())->getTestAreas(['is_open' => 1]);
        } else {
            $areas = (new AreaRepository())->getAreas(['is_open' => 1]);
        }
        $hot_cities = array_filter(explode(",", str_replace("，", ",", Config::getValue("hot_cities"))));
        return $this->apiResponse->success([
            'areas' => $areas,
            'hot_cities' => $hot_cities ?? []
        ]);
    }

    /**
     * 身份认证
     */
    public function auth_idcard()
    {
        $params = request()->all();
        if (empty($params['idcard_type_name']) || empty($params['idcard_type_no']) || empty($params['realname'])) {
            return retFail('参数错误！');
        }
        if ($params['idcard_type_name'] == 1) {
            $member = Member::where(['idcard' => $params['idcard_type_no']])->first(['id', 'username']);
            if ($member) {
                if ($member['id'] != UID) {
                    return retFail('昵称' . $member['username'] . ', 编号' . $member['id'] . '已认证该身份证号，如果不是你本人，请点击问题反馈');
                } else {
                    if ($member['idcard_status'] != 1) {
                        $this->memberRep->saveOrUpdate(['idcard_status' => 1], UID);
                    }
                    return retSuc([], '恭喜你，认证成功!');
                }
            }

            try {
                $res = (new AliCloudService())->authIdcard($params['realname'], $params['idcard_type_no']);
                if (!$res['success']) {
                    return retFail($res['msg']);
                }

                //处理业务逻辑 ToDo
                $sex = $res['data']['sex'] == '男' ? "M" : ($res['data']['sex'] == '女' ? 'F' : '');
                $birthday = substr($res['data']['birthday'], 0, 4) . '-' . substr($res['data']['birthday'], 4, 2) . '-' . substr($res['data']['birthday'], 6, 2);

                empty($sex) && $sex = getIDCardSex($params['idcard_type_no']);
                empty($birthday) && $birthday = getIDCardBirthday($params['idcard_type_no']);

                $update = [
                    'gender' => $sex,
                    'idcard_type' => $params['idcard_type_name'],
                    'realname' => $params['realname'],
                    'idcard' => $params['idcard_type_no'],
                    'birthday' => $birthday,
                    'idcard_status' => 1,
                ];

                $this->memberRep->saveOrUpdate($update, UID);
                if (!AccountRecord::where(["type" => 22, 'uid' => UID])->count("id")) {
                    $price = get_new_task_price(11);
                    //认证通过增加奖励
                    $this->memberRep->change_user_account(UID, null, null, 22, $price, null, 1, nextMonday());
                }
                return retSuc([], '恭喜你，认证成功');
            } catch (Exception $e) {
                return retFail($e->getMessage());
            }

        } else {
            if (isset($params['gender'])) {
                $gender = ($params['gender'] == '0') ? 'M' : 'F';
            } else {
                $gender = 'U';
            }

            $this->memberRep->saveOrUpdate([
                'gender' => $gender,
                'idcard_type' => $params['idcard_type_name'],
                'realname' => $params['realname'],
                'idcard' => $params['idcard_type_no'],
                'id_front_pic' => $params['id_front_pic'],
                'birthday' => $params['birthday'],
                'idcard_status' => 4,
            ], UID);

            return retSuc([], "提交成功，我们会在2小时内审核，审核结果会通过“月下比心服务号”通知你。");
        }
    }

    /**
     * 学历认证
     * @Author   thomashtao               bosslen
     * @DateTime 2022-04-07T15:29:09+0800
     * @return   [type]                   [description]
     */
    public function auth_education()
    {
        $params = request()->only("education_type", "education_number", "education_pic", "undergraduate");
        if (empty($params['education_type']) || $params['education_type'] == 3 && empty($params['education_number']) || $params['education_type'] == 4 && (empty($params['education_number']) || empty($params['undergraduate'])) || $params['education_type'] == 5 && (empty($params['education_pic']) || empty($params['undergraduate']))) {
            return retFail('参数错误！');
        }

        // 学信网在线验证码
        if ($params['education_type'] == 3) {
            return $this->memberRep->checkChsiCode($params, UID);
        } else {
            $update = [
                "undergraduate" => $params['undergraduate'],
                "education_type" => $params['education_type'],
                "education_number" => $params['education_number'],
                'education_pic' => $params['education_pic'],
                'status' => 4
            ];

            // 教留服认证
            $this->memberRep->saveOrUpdate($update, UID);
            return retSuc([], '提交成功，我们会在2小时内审核，审核结果会通过“月下比心服务号”通知你。');
        }
    }

    /**
     * 获取编辑信息
     * @Author   thomashtao               bosslen
     * @param string $value [description]
     */
    public function get_edit_init_data()
    {
        $type = request()->get("type");
        $member = $this->memberRep->getOne(UID);

        if ($type == 'edu' && in_array($member['status'], [1, 3, 4])) {
//            return $this->apiResponse->error('当前状态不允许编辑。', 400);
            return retSuc([
                'status' => 1,
                'member' => $member,
            ]);
        }

        return $this->apiResponse->success([
            'member' => $member,
            'current_status' => current_status(),
            'award_education_type' => get_new_task_price(10),
            'award_auth_idcard' => get_new_task_price(7),
            'education_type' => education_type()
        ]);
    }

    /**
     * 推荐好友列表
     * @Author   thomashtao               bosslen
     * @DateTime 2022-04-30T23:25:37+0800
     * @return   [type]                   [description]
     */
    public function recommend()
    {
        $filter['ruid'] = UID;
        $res = (new MemberMiniRecommendRepository())->getPages($filter, $this->pageSize, $this->pageNum);

        return $this->apiResponse->success($res);
    }

    /**
     * 推荐分享
     * @Author   thomashtao               bosslen
     * @DateTime 2022-04-01T00:32:37+0800
     * @return   [type]                   [description]
     */
    public function share()
    {
        $uid = md6(request()->get("id"), true);
        if (!$uid) {
            return $this->apiResponse->error("参数错误，请重新进入。", 400);
        }
        $enlist = $this->memberRep->getOne($uid);
        // if ($enlist['cancel'] == 0  && ![$wechat_admin_id, [5,10,12,20,1882,45009,75997,1029,42,44,14117,17966,2021]] ) {


        if (!$enlist) {
            return $this->apiResponse->success([
                'url' => "elect-pool/my",
                'errmsg' => "嘉宾不存在"
            ], "ok", 411);
        }

        if ($enlist['cancel'] == 0) {
            return $this->apiResponse->success([
                'url' => "elect-pool/my",
                'errmsg' => "对方账户已注销，不允许查看。"
            ], "ok", 411);
        }

        $wechat_admin_id = $this->memberRep->getIdByToken(request()->header("token"));
        $member = $this->memberRep->getOne($wechat_admin_id);
        if (!empty($wechat_admin_id)) {
            $enlist_price = (new EnlistRepository())->get_enlist_price($member, $enlist);
            $is_need_recharge = $this->memberRep->check_account_balance($wechat_admin_id, $enlist_price);

            // if ($enlist["open_share"] != 1 && !in_array($wechat_admin_id, [5, 10, 12, 20, 1882, 45009, 75997, 1029, 42, 44, 14117, 17966, 2021])) {
            //     return $this->apiResponse->success([
            //         'url' => "elect-pool/my",
            //         'errmsg' => $enlist["username"] . '已关闭资料访问开关，暂时不能访问哦。可能是已脱单或暂时不想被打扰，你可以看看其他嘉宾哦。现已为你跳转到网站首页！'
            //     ], "ok", 411);
            // }

            $result['enlist_price'] = $enlist_price;
            $result['is_need_recharge'] = $is_need_recharge;
        }

        if (trim($enlist['education']) == '博' && !is_null($enlist['doctor_college'])) {
            $school_name = $enlist['doctor_college'];
        } elseif (trim($enlist['education']) == '硕' && !is_null($enlist['master_college'])) {
            $school_name = $enlist['master_college'];
        } else {
            $school_name = $enlist['undergraduate'];
        }
        if (strpos($enlist['current_status'], '工作') !== false || $enlist['current_status'] == '其他') {
            $work = $enlist['occupation'];
        } else if (strpos($enlist['current_status'], '在读') !== false) {
            unset($enlist['education']);
            $work = $enlist['current_status'] . '-' . $enlist['profession'];
        } else {
            $work = $enlist['current_status'];
        }

        $share_title = $enlist["location"] . '-' . member_gender($enlist['gender']) . '-' . substr($enlist['birthday'], 2, 2) . '-' . $enlist["height"] . '-' . $school_name;

        if ($enlist['education']) {
            $share_title = $share_title . '-' . $enlist["education"];
        }

        $share_title = $share_title . '-' . $work . '-' . '坐标' . $enlist["residence"] . '-' . $enlist["hometown"] . '人';
        //判断
        $stepby = $this->memberRep->check_member_profile();

        if ($member) {
            $lcity = '不限';
            if ($member['lcity'] && is_str_has($member['lcity'], '市')) {
                $lcity = str_replace('市', '', $member['lcity']);;
            }

            if ($member['current_status'] && is_str_has($member['current_status'], '在读')) {
                $jump = Jump::where("id", "=", 39)->first();
            } else {
                $jump = Jump::where("city", "=", $lcity)->first();
            }

            if ($member['Latitude'] && $member['Longitude'] && $enlist['lcity']) {
                $show_city = ($enlist['lcity'] == $member['lcity']) ? $enlist['ldistrict'] : $enlist['lcity'];
                $enlist['jw_location'] = get_distance($member['Latitude'], $member['Longitude'], $enlist['Latitude'], $enlist['Longitude']) . ($show_city ? ('·' . $show_city) : '');
            }

            $result['jump'] = $jump;
            $result['member'] = $member;

            if (!empty($member['lcity'])) {
                $kefu = Kefu::query()->where(['city' => str_replace("市", "", $member['lcity'])])->first();

                if (!empty($kefu)) {
                    $result['group'] = [
                        'title' => $kefu['username'],
                        'content' => $kefu['content'],
                        'path' => $kefu['qrcode']
                    ];
                }
            }
        }

        $extra_ids = "7,10,11,12";
        $categories = $this->wechatMenusRep->getMemberCategoryForMember($extra_ids);
        $fields = $this->memberRep->getMemberFields();

        /*$elected = Enlist::where([
            'enlist_uid' => UID,
            'enlisted_uid' => $enlist['id']
        ])->orWhere([
            'enlisted_uid' => UID,
            'enlist_uid' => $enlist['id']
        ])->first();*/

        $elected = Enlist::query()
            ->whereRaw("(enlist_uid = " . UID . " and enlisted_uid=" . $enlist['id'] . ") or (enlist_uid = " . $enlist['id'] . " and enlisted_uid=" . UID . ")")
            ->first();

        $result['fields'] = $fields;
        $result['stepby'] = $stepby;
        $result['elected'] = $elected;
        $result['categories'] = $categories;
        $result['enlist_member'] = $enlist;
        $result['weixin_price'] = self::WEIXIN_PRICE;
        $result['group_link'] = C('tuodan_group');
        $result['open_fraud'] = open_fraud();

        // 检查是否获取微信了
        $is_get_wx = EnlistWeixin::where(['enlist_uid' => UID, 'enlisted_uid' => $enlist['id']])->count("id");
        if (!$is_get_wx) {//是否被获取
            $ew_count = EnlistWeixin::where(['enlisted_uid' => UID, 'enlist_uid' => $enlist['id']])->count("id");
            $is_get_wx = $ew_count > 0 ? 2 : 0;
        }
        $result['is_get_wx'] = $is_get_wx ?? 0;

        if (!empty($elected)) {
            $result['message'] = Msg::where([
                'type' => 3,
                'object_type' => "enlist",
                'object_id' => $elected['id']
            ])->first();
        }

        return $this->apiResponse->success($result);
    }

    public function delete_picture()
    {
        $picture_id = request()->post("picture_id");
        $wechat_admin_id = request()->get("wechat_admin_id");

        $mappingRep = new PictureMappingRepository();
        $picture_mapping = $mappingRep->getMapping([
//            'picture_id' => $picture_id,
            'id' => $picture_id,
            'object_id' => UID,
            'object_type' => "member"
        ]);
        if (!$picture_mapping)
            return retFail("图片不存在");

        $mappingRep->deletePicture($picture_mapping['id']);

        return $this->apiResponse->success([]);
    }

    public function update_gender()
    {
        $member = $this->memberRep->getOne(UID);
        if ($member['gender'] != 'U') {
            return $this->apiResponse->error("性别不能修改");
        }

        $gender = request()->post("gender");
        if (empty($gender) || !in_array($gender, ['M', "F"])) {
            return $this->apiResponse->error("性别错误");
        }

        $this->memberRep->updateFields(UID, ['gender' => $gender]);
        return $this->apiResponse->success([]);
    }

    /**
     * 保存位置
     * @Author   thomashtao               bosslen
     * @DateTime 2022-04-14T09:50:22+0800
     * @return   [type]                   [description]
     */
    public function edit_location()
    {
        $params = request()->all();
        if ($params['nation'] == '中国') {// 国内（包含 港澳台）
            $m_data['Longitude'] = $params['longitude'];
            $m_data['Latitude'] = $params['latitude'];
            $m_data['nation'] = $params['nation'];
            $m_data['lprovince'] = $params['province'];
            $m_data['lcity'] = $params['city'];
            $m_data['ldistrict'] = $params['district'];
        } else {// 国外
            $m_data['Longitude'] = $params['longitude'];
            $m_data['Latitude'] = $params['latitude'];
            $m_data['nation'] = $params['nation'];
            $m_data['lprovince'] = $params['ad_level_1'];
            $m_data['lcity'] = $params['ad_level_2'];
            $m_data['ldistrict'] = $params['locality'];
        }

        $this->memberRep->updateFields(UID, $m_data);

        Matchpool::where(['uid' => UID])->update(['longitude' => $params['longitude'], 'latitude' => $params['latitude']]);

        return $this->apiResponse->success([
            'city' => $params['city'],
            'district' => $params['district']
        ]);
    }

    public function my_stat()
    {
        $stats = $this->memberRep->getMyStat();
        return $this->apiResponse->success($stats);
    }

    /**
     * 检测是否关注公众号
     * @Author   thomashtao               bosslen
     * @DateTime 2022-07-21T11:35:45+0800
     * @return   [type]                   [description]
     */
    public function check_subscribe()
    {
        $is_subscribe = Member::where("id", "=", UID)->value("is_subscribe");

        $result = [
            'url' => C('service_subscribe_url'),//'https://mp.weixin.qq.com/s/LJXZPyuF5mdqjmFRE7iN7A',
            'is_subscribe' => $is_subscribe,
            'title' => '免费匹配聊天',
            'path' => '/Uploads/public/qrcode/bsblyfwh.jpg',
            'content' => '关注本硕博联谊服务号<br>回复<span style="color: #EF6243">1</span>免费匹配聊天<br>回复<span style="color: #EF6243">4</span>加入脱单群<br>回复<span style="color: #EF6243">城市名</span>加入城市互选池<br>回复<span style="color: #EF6243">省名</span>加入老乡互选池'
        ];

        return $this->apiResponse->success($result);
    }

    /**
     * 检测是否关注订阅号
     * @Author   thomashtao               bosslen
     * @DateTime 2022-07-21T11:35:45+0800
     * @return   [type]                   [description]
     */
    public function check_is_subscribe()
    {
        $offiaccount = request()->get("offiaccount");

        $unionid = Member::where("id", "=", UID)->value("unionid");

        if ($offiaccount) {
            $where['offiaccount'] = $offiaccount;
        }
        $where['unionid'] = $unionid;

        $res = OfficialAccountSubscribe::where($where)->first();
        $res['url'] = '';// 附近的人 未关注匹配池跳转到关注匹配池

        return $this->apiResponse->success($res);
    }

    /**
     * 提现金额
     * @Author   thomashtao               bosslen
     * @DateTime 2022-08-01T16:15:41+0800
     * @return   [type]                   [description]
     */
    public function withdraw()
    {
        $withdraw_price = floatval(request()->post("price"));
        if ($withdraw_price < 1) {
            return $this->apiResponse->error("最低提现1元");
        }

        $amount = Withdraw::where("uid", "=", UID)->where("create_time", "like", date("Y-m-d") . '%')->count("id");
        $withdraw_times = C("withdraw_times");
        if ($amount >= intval($withdraw_times))
            return $this->apiResponse->error("每日只能提现" . $withdraw_times . "次，明天再来提现吧！");

        $member = $this->memberRep->getOne(UID);

        if ($member['account'] < 0) {
            return $this->apiResponse->error("联谊币账户大于0才能提现");
        }

        if ($withdraw_price > $member['balance']) {
            return $this->apiResponse->error("提现金额不能高于账户余额");
        }

        if (empty($member['idcard']) || empty($member['realname'])) {
            return $this->apiResponse->error("你的账户未实名认证，暂时不能体现，请联系微信bsbly88。");
        }

        !$withdraw_price && $withdraw_price = 0.01;
        $mch_billno = date('YmdHi') . rand(1000, 9999);// 唯一订单号

        try {
            $res = $this->wechatRep->withdraw($mch_billno, $member['weapp_openid'], $withdraw_price);
            if ($res['status'] == 1) {
                //修改账户余额
                $m_data['balance'] = floatval($member['balance'] - $withdraw_price);
                $this->memberRep->updateFields(UID, $m_data);

                //增加支出记录
                $in_data['price'] = $withdraw_price;
                $in_data['uid'] = UID;
                $in_data['object_type'] = "withdraw";
                $in_data['create_time'] = date("Y-m-d H:i:s");
                Income::insert($in_data);

                //增加提现记录
                $wd_data['out_trade_no'] = $mch_billno;
                $wd_data['price'] = $withdraw_price;
                $wd_data['uid'] = UID;
                $wd_data['status'] = 1;
                $wd_data['create_time'] = date("Y-m-d H:i:s");
                Withdraw::insert($wd_data);

                return $this->apiResponse->success([], '提现成功');
            } else {
                return $this->apiResponse->error("提现失败！");
            }

        } catch (Exception $e) {
            return $this->apiResponse->error($e->getMessage());
        }
        // dump($withdraw_price);
    }

    // 获取脱单群二维码
    public function get_jump()
    {
        $skey = request()->get("skey");
        $filter = [];
        $skey = array_filter(explode(",", $skey));

        if (count($skey)) {
            $filter['jump_key'] = $skey;
        }

        $filter['status'] = 2;
        $jump = (new JumpRepository())->getPages($filter);
        return $this->apiResponse->success($jump);
    }

    //检查手机号码和实名认证
    public function check_idcard_mobile()
    {
        $stypeall = $this->memberRep->check_member_profile(true);

        if (in_array(99, $stypeall['type'])) {
            return $this->apiResponse->success(['type' => 99, "msg" => "请验证手机号"]);
        } else if (in_array(7, $stypeall['type'])) {
            return $this->apiResponse->success(['type' => 7, "msg" => "请先实名认证"]);
        } else {
            return $this->apiResponse->success(['status' => 1]);
        }
    }

    public function save_lastvisit()
    {
        $last_url = trim(request()->post("last_url"));
        if (!$last_url)
            return $this->apiResponse->success();

        $last_visit_id = Lastvisit::where("uid", "=", UID)->value("id");
        if ($last_visit_id) {
            Lastvisit::where("id", "=", $last_visit_id)->update([
                'last_url' => $last_url,
                'type' => 2,
            ]);
        } else {
            Lastvisit::insert([
                'last_url' => $last_url,
                'uid' => UID,
                'type' => 2,
                'create_time' => date("Y-m-d H:i:s")
            ]);
        }

        return $this->apiResponse->success([], 'success');
    }

    /**
     * jump详情
     * @Author   thomashtao               bosslen
     * @DateTime 2022-10-04T18:04:14+0800
     * @return   [type]                   [description]
     */
    public function get_jump_info()
    {
        $push_id = request()->get("id");
        if (!$push_id)
            return $this->apiResponse->error("发帖信息不存在");
        $res = Jump::where("id", "=", $push_id)->first();
        $res['member'] = $this->memberRep->getOne(UID);
        $res['check'] = $this->memberRep->check_member_profile(true, true);
        $res['my_push'] = PublicAccountPush::where(['uid' => UID, 'status' => 1])->first();
        return $this->apiResponse->success($res);
    }

    /**
     * pages/member/index页面 脱单群按钮接口
     */
    public function get_jump_group()
    {
        $member = $this->memberRep->getOne(UID);
        $res['gender'] = $member['gender'];
        $default = false;
        if ($member['lcity']) {
            $city = str_replace('市', '', $member['lcity']);
            $jump = Jump::where("city", "=", $city)->first();
            if (empty($jump)) {
                $default = true;
            }
        } else {
            //$default = true;
            $res['no_auth_location'] = true;
        }
        if ($default) { // 默认
            if (isStudent($member['current_status'])) {// 在读
                $jump = Jump::where(['id' => 39])->first();
            } else {// 工作
                $jump = Jump::where(['id' => 34])->first();
            }
        }
        $res['jump'] = $jump;
        return $this->apiResponse->success($res);
    }

    /**
     * 用于单个弹窗编辑资料
     */
    public function model_fields()
    {
        $member = $this->memberRep->getOne(UID);
        $model_fields = $this->memberRep->getMemberQuickFields();

        return $this->apiResponse->success([
            'member' => $member,
            'model_fields' => $model_fields
        ]);
    }

    /**
     * 检验微信二维码
     */
    public function check_exist_wxqrcode()
    {
        $uid = request()->get("uid");
        $member = $this->memberRep->getOne($uid);

        /*        if (empty($member['weixin_qrcode_pic'])) {
                    return $this->apiResponse->success(['status' => 0]);
                }*/

        // 二维码有效
        if ($member['enable_wx_qrcode'] == 1) {
            return $this->apiResponse->success(['status' => 1]);
        }

//        $res = check_img_qr_code($member['weixin_qrcode_pic']);
        $res = cos_check_qrcode($member['weixin_qrcode_pic']);

        $res = true;
        if ($res) {
            return $this->apiResponse->success(['status' => 1]);
        } else {
            return $this->apiResponse->success(['status' => 0]);
        }
    }

    /**
     * 推送会员详情-小编
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function desc()
    {
        $allow_list = explode(',', C("get_member_desc"));//允许访问的用户
        if (!in_array(UID, $allow_list)) {
            return $this->apiResponse->error("没有查询权限");
        }
        $id = request()->get("id");// 用户id
        if (intval($id) == 0) {
            return $this->apiResponse->error("参数获取失败");
        }
        $pages = 'pages/share/member?uid=' . md6($id);// 要生成的小程序页面
        $shortlink = ShortLink::query()->where(['uid' => $id, 'pages' => $pages])->first();
        if ($shortlink) { // 存在，直接取表里数据
            $link = $shortlink['short_link'];
        } else {// 不存在，生成短链接
            // $result = $this->wechatRep->getShortLink($pages, '个人资料', true);
            // $link = $result['link'];
            // // 写表
            // $add['uid'] = $id;
            // $add['search'] = UID;
            // $add['pages'] = $pages;
            // $add['short_link'] = $link;
            // $add['create_time'] = date('Y-m-d H:i:s');
            // $add['update_time'] = date('Y-m-d H:i:s');
            // ShortLink::insert($add);
        }
        $member = $this->memberRep->getOne($id);
        $kefu = Kefu::query()->where("uid", "=", UID)->first();
        $user_desc = $this->memberRep->get_user_desc($member->toArray());

        $count = Autoreply::where(['appid' => $kefu['jump_id'], 'key' => $id])->count();

        if ($count == 0 && $kefu['jump_id']) {
            $in['appid'] = $kefu['jump_id'];
            $in['key'] = $id;
            $in['create_time'] = date('Y-m-d H:i:s');
            $in['update_time'] = date('Y-m-d H:i:s');
            $last_id = AutoreplyGroup::insertGetId($in);

            $insert['group_id'] = $last_id;
            $insert['appid'] = $kefu['jump_id'];
            $insert['type'] = 'text';
            $insert['key'] = $id;
            $insert['content'] = '<a data-miniprogram-appid="wx0842f4f0457b62b8" data-miniprogram-path="' . $pages . '" data-miniprogram-nickname="本硕博联谊脱单" data-miniprogram-type="text">' . $user_desc . '</a>';
            Autoreply::insert($insert);
        }

        $res['member'] = $member;
        if ($member['idcard_status'] == 1) {
            $res['show'] = "【】" . $user_desc . "，更多点击" . $link;
        } else {
            $res['show'] = '请小编提醒该用户完成实名认证之后再来发布朋友圈！';
        }
        $res['show'] .= "\n\n" . ($kefu['fatie_summary' . $this->getFatieFields()] ?? "");

        $res['kefu'] = $kefu;
        return $this->apiResponse->success($res);
    }

    private function getFatieFields()
    {
        $rand = rand(0, 1);
        if ($rand) {
            return "1";
        }
        return "";
    }

    //骗子展示
    public function fraud()
    {
        $params['fraud_ids'] = Fraud::where('id', '>', 0)->get('uid');
        $res = $this->memberRep->getFraudPages($params, $this->pageSize, $this->pageNum);
        return $this->apiResponse->success($res);
    }

    //  增加访问记录
    public function add_visit()
    {
        $to_uid = intval(request()->post("to_uid"));
        $type = intval(request()->post("type"));
        $object_id = intval(request()->post("object_id"));

        if (empty($to_uid))
            return $this->apiResponse->error("数据错误");
        // 判断是否已解锁
        (new MemberVisitRepository())->saveOrUpdate(UID, $to_uid, $type ?? "", $object_id ?? "");
        return $this->apiResponse->success();
    }

    /**
     * 访客记录列表
     * @return []
     */
    public function visit_list()
    {
        $params['mv.df_uid'] = UID;
//        $params['m.status'] = 1;
        $res = (new MemberVisitRepository())->getVisitPages($params, $this->pageSize, $this->pageNum);

        if ($this->pageNum == 1) {
            $member = $this->memberRep->getOne(UID);
            $res['is_need_charge'] = $member['total_account'] < self::OPEN_LOCK_VISIT ? 1 : 0;
        }

        return $this->apiResponse->success($res);
    }

    /**
     * 解锁访客记录
     * @return []
     */
    public function open_visit()
    {
        $uid = intval(request()->post("uid"));
        $visit_member = $this->memberRep->getOne($uid);

        if (empty($visit_member)) {
            return retFail("解锁嘉宾不存在");
        }
        if ($visit_member['is_forbidden'] == 2) {
            return retFail("嘉宾账号已被禁用");
        }
        if ($visit_member['cancel'] == 0) {
            return retFail("嘉宾已注销不允许解锁");
        }
        $member = $this->memberRep->getSimpleMember(UID, 3);
        if ($member['total_account'] < self::OPEN_LOCK_VISIT) {
            return retFail("账户余额不足");
        }
        $res = (new MemberVisitOrderRepository())->openLock($uid, UID, self::OPEN_LOCK_VISIT);

        if ($res) {
            return retSuc([], "解锁成功");
        } else {
            return retFail("解锁失败");
        }
    }

    /**
     * 删除访客记录
     * @return []
     */
    public function del_visit()
    {
        $uid = intval(request()->post("uid"));
        $visit_member = $this->memberRep->getOne($uid);

        if (empty($visit_member)) {
            return $this->apiResponse->error("嘉宾不存在");
        }

        if ($visit_member['is_forbidden'] == 1) {
            return $this->apiResponse->error("嘉宾账号已被禁用");
        }

        $res = (new MemberVisitRepository())->delete($uid, UID);
        if ($res) {
            return $this->apiResponse->success([], "删除成功");
        } else {
            return $this->apiResponse->error("删除失败");
        }
    }

    //封禁时间
    public function ban()
    {
        $member = MemberBan::where(['uid' => UID, 'status' => 1])->first();
        return $this->apiResponse->success($member);
    }

    // 二维码
    public function qrcode()
    {
        try {
            $res = (new MemberQrcodeRepository())->getPath(UID);

            return $this->apiResponse->success(['path' => $res]);
        } catch (Exception $e) {
            return $this->apiResponse->error($e->getMessage());
        }
    }

    public function delete_account_record()
    {
        $id = request()->get("id");
        if (!$id)
            return $this->apiResponse->error("数据错误，请重试");

        $record = AccountRecord::where(['id' => $id])->first();
        if ($record['uid'] != UID) {
            return $this->apiResponse->error("无权限删除");
        }

        AccountRecord::where("id", "=", $id)->update(['is_delete' => 2, 'deleted_at' => date("Y-m-d H:i:s")]);
        return $this->apiResponse->success([], "success");
    }

    //聊天信息
    public function chat()
    {
        $params = request()->all();
        $params['uid'] = UID;
        if (empty($params['df_uid'])) {
            return $this->apiResponse->error("参数错误");
        }

        $res = (new ChatRepository())->getList($params, $this->pageSize, $this->pageNum);

        return $this->apiResponse->success($res);
    }

    public function simple()
    {
        return retSuc([
            'member' => $this->memberRep->getSimpleMember(UID, 3)
        ]);
    }

}